from rest_framework import serializers

from apps.goods.models import SKUImage
from apps.goods.models import SKU

from fdfs_client.client import Fdfs_client


class ImageSeriazlier(serializers.ModelSerializer):

    sku = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = SKUImage
        fields = ['sku', 'image', 'id']

    def update(self, instance, validated_data):
        # 上传图片
        # 创建fdfs
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 接受参数
        upload_image = validated_data.get('image')
        # 上传数据到fdfs
        result = client.upload_by_buffer(upload_image.read())
        # 判断是否上传成功
        if result['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上上传失败')
        # 更新数据库(保存image路径地址)
        instance.image = result.get('Remote file_id')
        instance.save()
        return instance


class SKUSerializer(serializers.ModelSerializer):
    """保存图片时的sku列表"""
    class Meta:
        model = SKU
        fields = ['id', 'name']